/*
 * ConnectionPool.cpp
 *
 *  Created on: 2013年7月30日
 *      Author: sun
 */

#include "ConnectionPool.h"
#include "Log.h"

namespace sdfs {

ConnectionPool::ConnectionPool(IConnector* connector,
		int poolsize, bool isBlock) {
	m_connector = new LinkedList<IConnector*>();
	m_nSize = poolsize;
	for(int i = 0 ; i < poolsize ; ++i)
	{
		IConnector* p_clone = connector->Clone();
		if(p_clone != NULL)
		{
			m_connector->Push(p_clone);
		}
		else
		{
			Log::Warning("create connection failture!");
			delete p_clone;
			i--;
		}
	}
	//BuildConnections();
}

ConnectionPool::~ConnectionPool() {
	CloseConnections();
	m_mutex.Lock();
	delete m_connector;
	m_connector = NULL;
	m_mutex.Unlock();
	Log::Debug("~ConnectionPool() end");
}

IConnector *ConnectionPool::GetConnection()
{
	IConnector *connector = NULL;
	m_mutex.Lock();
	connector = m_connector->Pop();
	m_mutex.Unlock();
	return connector;
}

int ConnectionPool::ReturnConnection(IConnector *connector)
{
	int result;
	m_mutex.Lock();
	result = m_connector->Push(connector);
	m_mutex.Unlock();
	return result;
}

void ConnectionPool::BuildConnections()
{
	IConnector *connector = NULL;
	m_mutex.Lock();
	for(int i = 0 ; i < m_connector->Size() ; ++i)
	{
		connector = m_connector->GetAt(i);
		if(connector != NULL)
			connector->Connect();
	}
	m_mutex.Unlock();
}

void ConnectionPool::CloseConnections()
{
	m_mutex.Lock();
	while(m_connector->Size()>0)
	{
		IConnector *connector = m_connector->Pop();
		connector->DisConnect();
		delete connector;
	}
	m_mutex.Unlock();
}


} /* namespace sdfs */
